from app.models.database import db
from datetime import datetime

class ExecutionStepRecord(db.Model):
    """执行步骤记录模型"""
    __tablename__ = 'execution_step_record'
    
    id = db.Column(db.Integer, primary_key=True)
    record_id = db.Column(db.Integer, db.ForeignKey('execution_record.id'), nullable=False)
    step_id = db.Column(db.Integer, db.ForeignKey('scene_step.id'))
    parent_id = db.Column(db.Integer, db.ForeignKey('execution_step_record.id'))
    type = db.Column(db.String(20), nullable=False)  # api, script, condition, loop
    name = db.Column(db.String(100))
    status = db.Column(db.String(20), default='pending')  # pending, running, success, failed, skipped
    start_time = db.Column(db.DateTime)
    end_time = db.Column(db.DateTime)
    duration = db.Column(db.Integer)  # 执行时长（毫秒）
    request = db.Column(db.JSON)  # 请求信息
    response = db.Column(db.JSON)  # 响应信息
    error = db.Column(db.Text)  # 错误信息
    
    # 关联到执行记录
    record = db.relationship('ExecutionRecord', back_populates='steps')
    
    # 关联到场景步骤
    step = db.relationship('SceneStep', back_populates='execution_records')
    
    # 关联到父步骤和子步骤
    parent = db.relationship('ExecutionStepRecord', remote_side=[id], backref=db.backref('children', order_by=start_time))
    
    def to_dict(self):
        result = {
            'id': self.id,
            'record_id': self.record_id,
            'step_id': self.step_id,
            'parent_id': self.parent_id,
            'type': self.type,
            'name': self.name,
            'status': self.status,
            'start_time': self.start_time.strftime('%Y-%m-%d %H:%M:%S') if self.start_time else None,
            'end_time': self.end_time.strftime('%Y-%m-%d %H:%M:%S') if self.end_time else None,
            'duration': self.duration,
            'request': self.request,
            'response': self.response,
            'error': self.error
        }
        
        # 添加子步骤
        if not self.parent_id:  # 只为顶级步骤添加子步骤
            result['children'] = [child.to_dict() for child in self.children]
        
        return result